package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.warning.domain.entity.Device;
import com.ruoyi.warning.domain.entity.DevicesLog;
import com.ruoyi.warning.mapper.DevicesLogMapper;
import com.ruoyi.warning.service.IDevicesLogService;
import com.ruoyi.warning.service.IDevicesService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-03-26
 */
@Service
public class DevicesLogServiceImpl extends ServiceImpl<DevicesLogMapper, DevicesLog> implements IDevicesLogService {
    @Resource
    private DevicesLogMapper devicesLogMapper;
    @Resource
    private IDevicesService devicesService;
    @Override
    public void refreshLog() {
        List<Device> list = devicesService.list();
        List<DevicesLog> list1 = new java.util.ArrayList<>();
        java.time.LocalDateTime currentTime = java.time.LocalDateTime.now();
        for (Device device : list) {
            DevicesLog devicesLog = new DevicesLog();
            BeanUtils.copyProperties(device,devicesLog);
            devicesLog.setInserted(currentTime);
            list1.add(devicesLog);
        }
        this.saveBatch(list1);
    }

    @Override
    public Object getDevicesLog(String id,String startTime) {
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 当前时间
        String now = currentTime.format(formatter);

        // 1 小时前
        String oneHourAgo = currentTime.minusHours(1).format(formatter);

        // 4 小时前
        String fourHoursAgo = currentTime.minusHours(4).format(formatter);

        // 1 天前
        String oneDayAgo = currentTime.minusDays(1).format(formatter);

        // 一周前
        String oneWeekAgo = currentTime.minusWeeks(1).format(formatter);

        // 一个月前
        String oneMonthAgo = currentTime.minusMonths(1).format(formatter);

        LambdaQueryWrapper<DevicesLog> queryWrapper = new QueryWrapper<DevicesLog>().lambda()
                .eq(DevicesLog::getDeviceId, id)
                .gt(DevicesLog::getInserted, oneHourAgo)
                .lt(DevicesLog::getInserted, now);
        List<DevicesLog> list = this.list(queryWrapper);
        return list;
    }
}
